package i18n

import (
	"gitee.com/shoyer/logger"

	"github.com/BurntSushi/toml"
	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

var (
	bundlec *i18n.Bundle
	config  *Config
)

type Config struct {
	// 本地化文件路径
	Paths []string
}

// Init init locale
func Init(c *Config) error {
	config = c

	// logger.Print(language.SimplifiedChinese.String())
	bundle := i18n.NewBundle(language.English)
	bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)

	for _, v := range c.Paths {
		bundle.MustLoadMessageFile(v)
	}
	// bundle.MustLoadMessageFile("resources/locales/en.toml")    // 英文
	// bundle.MustLoadMessageFile("resources/locales/zh.toml")    // 简体中文
	// bundle.MustLoadMessageFile("resources/locales/zh-TW.toml") // 繁体中文

	bundlec = bundle

	logger.Debugf("Load locale successfully.")

	return nil
}

func checkConfig() {
	if config == nil || bundlec == nil {
		logger.Fatalf("i18n config not ok, pls check!!!")
	}
}

// GetLocalizer GetLocalizer
func GetLocalizer(locale string) *i18n.Localizer {
	checkConfig()
	return i18n.NewLocalizer(bundlec, locale)
}

// Localize params only accept one item, others will be ignored.
func Localize(locale string, messageID string, params ...map[string]interface{}) string {
	if locale == "" {
		locale = "en"
	}

	localized, err := GetLocalizer(locale).Localize(&i18n.LocalizeConfig{
		MessageID:    messageID,
		TemplateData: params,
	})

	if err != nil {
		logger.Warn(err)
		return messageID
	}

	return localized
}

// L alias of Localize, params only accept one item, others will be ignored.
func L(locale string, messageID string, params ...map[string]interface{}) string {
	return Localize(locale, messageID, params...)
}
